#!/bin/bash
set -e
export PATH="$SNAP/usr/sbin:$SNAP/usr/bin:$SNAP/sbin:$SNAP/bin:$PATH"
ARCH="$($SNAP/bin/uname -m)"
export LD_LIBRARY_PATH="$SNAP_LIBRARY_PATH:$LD_LIBRARY_PATH:$SNAP/lib:$SNAP/usr/lib:$SNAP/lib/$ARCH-linux-gnu:$SNAP/usr/lib/$ARCH-linux-gnu"

source $SNAP/actions/common/utils.sh

exit_if_service_not_expected_to_start flanneld

# Allow some slack for containerd and etcd to start
# so we avoid this edge case: https://forum.snapcraft.io/t/restarting-services-from-configure-hook-race-condition/2513/13
sleep 5

n=0
until [ $n -ge 10 ]
do
  test -e "$SNAP_DATA/args/flannel-network-mgr-config" && test -e "$SNAP_DATA/args/flanneld" && break
  echo "Waiting for flannled configuration to appear. (attempt $n)"
  n=$[$n+1]
  sleep 2
done

# TODO rewrite for snaps
etcd_endpoints="$(cat $SNAP_DATA/args/flanneld | grep "etcd-endpoints" | tr "=" " "| awk '{print $2}')"
cert_file="$(cat $SNAP_DATA/args/flanneld | grep "etcd-certfile" | tr "=" " "| awk '{print $2}')"
cert_file="$(eval echo $cert_file)"
key_file="$(cat $SNAP_DATA/args/flanneld | grep "etcd-keyfile" | tr "=" " "| awk '{print $2}')"
key_file="$(eval echo $key_file)"
ca_file="$(cat $SNAP_DATA/args/flanneld | grep "etcd-cafile" | tr "=" " "| awk '{print $2}')"
ca_file="$(eval echo $ca_file)"
# flannel requires etcd api v2
export ETCDCTL_API=2


# TODO get this from a file
data="$(cat $SNAP_DATA/args/flannel-network-mgr-config)"

if ! "${SNAP}/etcdctl" --endpoint "${etcd_endpoints}" --cert-file "${cert_file}" --key-file "${key_file}" --ca-file "${ca_file}" rm "/coreos.com/network/config"; then
  echo "/coreos.com/network/config is not in etcd. Probably a first time run."
fi

"${SNAP}/etcdctl" --endpoint "${etcd_endpoints}" --cert-file "${cert_file}" --key-file "${key_file}" --ca-file "${ca_file}" set "/coreos.com/network/config" "$data"

# This is really the only way I could find to get the args passed in correctly.
declare -a args="($(cat $SNAP_DATA/args/flanneld))"
export CORE_LD_LIBRARY_PATH="$SNAP/../../core18/current/lib/$ARCH-linux-gnu"
export LD_LIBRARY_PATH="$CORE_LD_LIBRARY_PATH:$LD_LIBRARY_PATH"
exec "$SNAP_DATA/opt/cni/bin/flanneld" "${args[@]}"
